"use strict";

const Service = require("egg").Service;
const https = require('https');
const querystring = require('querystring');
class BaiDuApiService extends Service {
  // 获取oss文件上传token

  
  async getStsToken() {
      try {
          const param = querystring.stringify({
              'grant_type': 'client_credentials',
              'client_id': 'dmoQZ9SGY0nzbVruBgQ5wC8r',
              'client_secret': 'HVmdYU13io946QLWZaTg3I51s5PnkZMg'
          });
  
          const options = {
              hostname: 'aip.baidubce.com',
              port: 443,
              path: '/oauth/2.0/token?' + param,
              method: 'POST'
          };
  
          const req = https.request(options, res => {
              let data = '';
              res.on('data', chunk => {
                  data += chunk;
              });
              res.on('end', () => {
                  const result = JSON.parse(data);
                  return ormSuccess({
                      refresh_token: result.refresh_token,
                      expires_in: result.expires_in,
                      session_key: result.session_key,
                      access_token: result.access_token,
                      scope: result.scope,
                      session_secret: result.session_secret,
                  });
              });
          });
  
          req.on('error', error => {
              throw '百度飞桨配置错误';
          });
          
          req.end();
      } catch (err) {
          if (err.response && err.response.data.error_description) {
              throw err.response.data.error_description;
          } else {
              throw '百度飞桨配置错误';
          }
      }
  }
  


//   /**
//    * @description 删除oss图片
//    * @param {*} ids 图片路径集合
//    * @returns
//    */
//   async deleteOssImg(ids) {
//     try {
//       const client = new OSS({
//         region: this.config.oss.region,
//         accessKeyId: this.config.oss.accessKeyId,
//         accessKeySecret: this.config.oss.accessKeySecret,
//         bucket: this.config.oss.bucketName,
//       });
//       const res = await client.deleteMulti(ids, {
//         quiet: true,
//       });
//       return this.ctx.helper.ormSuccess(res);
//     } catch (err) {
//       return this.ctx.helper.ormError(err);
//     }
//   }
}

module.exports = BaiDuApiService;
